package com.wht.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author wanghaotian
 * time:2022/11/17,0017 15:30
 * description:
 */

public class JDBCUtils {
    private static DataSource dataSource = null;
    static {
        try {
            //创建properties
            Properties properties = new Properties();
            //获取字节输入流
            InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            //加载
            properties.load(in);
            //获取连接池
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接对象方法
    public static DataSource getDs(){
        return dataSource;
    }
    public  static Connection getConnectionFromPool(){
        Connection connection=null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  connection;
    }
    //释放资源
    public static  void closeResources(Connection con, Statement stmt, ResultSet rs){
        //5.关闭资源
        try {
            if(con!=null){
                con.close();
            }
            if(stmt!=null){
                stmt.close();
            }
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
